
******************************
******************************
** Statistics for sectio A6 **
******************************
******************************
cap log close
log using "/Users/linnamarten/Dropbox (Personal)/Politiker_geografi/Bygglov/permit_appeal.log", replace 
gl dat "/Users/linnamarten/Dropbox (Personal)/Politiker_geografi/Bygglov" 


**********************************
** Permits at county level 2017 **
**********************************
use "$dat/permits_county_2017.dta", clear 
cap drop county
g county=""
loc j=0
foreach x in Stockholm x Uppsala Södermanland Östergötland Jönköping Kronoberg Kalmar Gotland Blekinge x Skåne Halland ///
VästraGötaland x x Värmland Örebro Västmanland Dalarna Gävleborg Västernorrland Jämtland Västerbotten Norrbotten  {
loc ++j
di `j' "`x'"
if inlist(`j',2,11,15,16) sum county_num
else replace county="`x'" if county_num==`j'
}

save "$dat/permits_county_2017.dta", replace
*****************
*** Appeals *****
*****************

use  "$dat/appeal.dta", clear

replace K="Ställningstagande" if K=="Ställningstagande/Besluttyp"

foreach var of varlist * {
   rename `var' `=`var'[1]' 
}
drop in 1 
destring, replace 



ren Ärendetyp Arendetyp
ren Ärendemening Arendemening
ren Ärenderubrik Arenderubrik
ren Åtgärd Atgard

rename _all, lower

ren länstyrelse county

cap drop bostad bygglov flerbostadshus enbostadshus radhus fritidshus

replace county=trim(county)

g year=regexs(0) if regexm(inkostdatum, "^[0-9][0-9][0-9][0-9]")
destring year, replace

g nybyggnad=regexs(0) if regexm(inkostdatum, "^[0-9][0-9][0-9][0-9]")


*ärendemening missing for Gävleborg, Halland, Västmanland, Östergötland in 2017
replace arendemening=arenderubrik if mi(arendemening)

foreach x in tillbyggnad strandskydd enbostadshus småhus flerbostadshus radhus fritidshus  ///
parhus modulhus modulbost bostadsmodul boendepaviljong lägenhet studentbostäder {
g `x'=regexs(0) if regexm(arendemening, "`x'")
}

g tvåbostadshus=regexs(0) if regexm(arendemening, "t*T*våbostadshus")
tab tvåbostadshus
g flerfamiljshus=regexs(0) if regexm(arendemening, "flerfamiljs*e*hus")
tab flerfamiljshus
g enbostadshus2=regexs(0) if regexm(arendemening, "e*E*n-*bostads*hus")
tab enbostadshus2
g flerbostadshus2=regexs(0) if regexm(arendemening, "f*F*ler-*bostadshus")
tab flerbostadshus2
g modulhus2=regexs(0) if regexm(arendemening, "modulbost")
tab modulhus2

foreach x in enbostadshus2 radhus parhus tvåbostadshus småhus {
replace enbostadshus=`x' if mi(enbostadshus)
}

foreach x in flerbostadshus2 flerfamiljshus modulhus modulhus2 bostadsmodul boendepaviljong lägenhet studentbostäder {
replace flerbostadshus=`x' if mi(flerbostadshus)
}


foreach x in nybyggnad tillbyggnad strandskydd enbostadshus flerbostadshus  fritidshus {
ren `x' `x'_ 
g `x'=(!mi(`x'_))
drop `x'_
}


** check counties to see which ones have enough info  ***
tab county  year if arendetyp=="Överklagande bostäder" // 13, almost all start 2017
bys county : egen temp=max(arendetyp=="Överklagande bostäder") if year==2017
tab county  if temp==0 // Dalarna, Gotland, Kronoberg, Norrbotten, Södermanland, Västra Götaland
*Kronoberg, Gotland missing ärendetyp but have ärendemening 2017 (can not distinguish type of building)
* the rest mix appeals for houses with other type of buildings


*check remaining 13
foreach x in Gävleborg Halland Jämtland Jönköping Kalmar Skåne Stockholm Uppsala Värmland Västerbotten Västernorrland Västmanland Östergötland {
display "`x'"	
tab arendetyp if year==2017 & county =="`x'"
}

* check share where we can classify type of building ***

g classify=(flerbostadshus==1 |enbostadshus==1)

foreach x in Gävleborg Halland Jämtland Jönköping Kalmar Skåne Stockholm Uppsala Värmland Västerbotten Västernorrland Västmanland Östergötland {
display "`x'"	
sum classify  if year==2017 & arendetyp=="Överklagande bostäder" & county =="`x'"
}

*also check for sample that lack  arendetyp=="Överklagande bostäder"
foreach x in Dalarna Gotland Kronoberg Norrbotten Södermanland VästraGötaland {
display "`x'"	
sum classify if year==2017  & county =="`x'" //(25-40%)
}

*over 50 % classified and arendetyp=="Överklagande bostäder" gives 10 counties
gl samplist Halland Jämtland Jönköping Skåne Stockholm Uppsala Värmland Västerbotten Västmanland Östergötland 

*extra check 
g samp=.
foreach x in $samplist  {
replace samp=1 if county =="`x'"
sum classify  if year==2017 & arendetyp=="Överklagande bostäder" & county =="`x'"
}


*look if there are additional search words to add
*list arendemening if year==2017 & samp==1 & classify==0 & arendetyp=="Överklagande bostäder"

*check the ones with few matches 0-40 %
* Västernorrland, Kalmar,  Gävleborg
*list arendemening if year==2017 & samp!=1 & classify==0 & arendetyp=="Överklagande bostäder"


tab flerbostadshus if samp==1 & year==2017 & arendetyp=="Överklagande bostäder" // 155
tab enbostadshus if samp==1 & year==2017 & arendetyp=="Överklagande bostäder" // 361


*number of building permits  per kategory and county in 2017 according to our bilding permits data

bys county year: egen appeal_onefam=sum(enbostadshus)
bys county year: egen appeal_multifam=sum(flerbostadshus)
keep if year==2017 & arendetyp=="Överklagande bostäder"

merge m:1 county using "$dat/permits_county_2017.dta"
drop if _merge==2 // Blekinge, Örebro
drop _merge


*check for sample where at least 50 % classify
bys county : egen share=mean(classify)
tab county share 

egen tag=tag(county)


*calculate all appeals/permits per county
g share_multifam=appeal_multifam/multifam
g share_onefam=appeal_onefam/onefam

sum share_multifam if tag==1 & share>=0.50 // 27 %
sum share_onefam if tag==1 & share>=0.50 // 7 %
sum share_multifam if tag==1 & share>=0.70 // 32 %
sum share_onefam if tag==1 & share>=0.70 // 9 %

*calculate all appeals/all permits
cap drop temp
loc x 70 // 50
g temp=1 if share>=0.`x'  & !mi(share)

tab county if temp==1
egen multifam_`x'=sum(multifam) if tag==1 & temp==1
egen onefam_`x'=sum(onefam) if tag==1 & temp==1
egen appeal_onefam_`x'=sum(enbostadshus) if temp==1
egen appeal_multifam_`x'=sum(flerbostadshus) if temp==1

g share_multifam_`x'=appeal_multifam_`x'/multifam_`x' 
g share_onefam_`x'=appeal_onefam_`x'/onefam_`x' 

sum share_multifam_* share_onefam_*
sum appeal_multifam_`x' appeal_onefam_`x' if temp==1

drop appeal_onefam_* appeal_multifam_*  multifam_* onefam_* share_*

*0.26 and 0.07 for 50%-limit 10 counties // 155 multi 361 sing
*0.29 and 0.08 for 70%-limit 7 counties, 149 multi 335 sing


log close 

******************
******************
** Table A2  *****
******************
******************

*************************
****    Master do-file   *****
*************************

clear
set more off
log close
sysdir set PLUS c:\ado\plus\b\
set scheme lean2

cd "D:\Userfiles\Personal\gabki722\Neighborhood Preferences\Matz"

global output "D:\Userfiles\Personal\gabki722\Neighborhood Preferences\Matz\Analysis\Output"
global input "D:\Userfiles\Personal\gabki722\Neighborhood Preferences\Matz\Analysis\Data"
global input2 "D:\Userfiles\Projects\PoorHousing"

global code1 "D:\Userfiles\Personal\gabki722\Neighborhood Preferences\Matz\Build\Code"
global code2 "D:\Userfiles\Personal\gabki722\Neighborhood Preferences\Matz\Analysis\Code"

global source "D:\Data\GeoSweden\GeoSweden 2.0\Fastighet"
global source2 "D:\Data\GeoSweden\GeoSweden 2.0\Basdata"
global source3 "D:\Data\GeoSweden\GeoSweden 2.0\Louise_Lisa"

log using "$output\masterlog", replace

******************************************************************************

* Build
do "$code1\Individ_bas"
do "$code1\Indink"
do "$code1\fastsd"
do "$code1\fastsoc"
do "$code1\fast2017"

* Analysis
do "$code2\Graph_summarystat"


***********************************
*****   individ bas       *********
***********************************
clear
set more off
sysdir set PLUS c:\ado\plus\b\
set scheme lean2

cd "D:\Userfiles\Personal\gabki722\Neighborhood Preferences\Matz"

global output "D:\Userfiles\Personal\gabki722\Neighborhood Preferences\Matz\Analysis\Output"
global input "D:\Userfiles\Personal\gabki722\Neighborhood Preferences\Matz\Analysis\Data"

global source "D:\Data\GeoSweden\GeoSweden 2.0\Fastighet"
global source2 "D:\Data\GeoSweden\GeoSweden 2.0\Basdata"
global source3 "D:\Data\GeoSweden\GeoSweden 2.0\Louise_Lisa"

******************************************************************************

* Individuals with link to properties 2017

use "$source2\IndData1990_2017.dta", clear
keep IBFLopNr FoddAr

merge 1:m IBFLopNr using "$source\BefFast2017", keepusing(IBFFastLopNr) keep(mat mas) nogen
rename IBFFastLopNr fast2017
duplicates drop IBFLopNr, force

rename IBFLopNr ibflopnr
rename FoddAr foddar
keep ibflopnr foddar fast*
order ibflopnr foddar fast*

compress
save "$input\indfast", replace


**************************
***       Indink      ****
**************************
clear
set more off
sysdir set PLUS c:\ado\plus\b\
set scheme lean2

cd "D:\Userfiles\Personal\gabki722\Neighborhood Preferences\Matz"

global output "D:\Userfiles\Personal\gabki722\Neighborhood Preferences\Matz\Analysis\Output"
global input "D:\Userfiles\Personal\gabki722\Neighborhood Preferences\Matz\Analysis\Data"

global source "D:\Data\GeoSweden\GeoSweden 2.0\Fastighet"
global source2 "D:\Data\GeoSweden\GeoSweden 2.0\Basdata"
global source3 "D:\Data\GeoSweden\GeoSweden 2.0\Louise_Lisa"

******************************************************************************

* Program

capture program drop genindinc
program genindinc
args yr inkforv inkdisp KapInk

use "$input\kpi", clear
keep if year == `yr'
global kpi = kpi[1]

use "$input\indfast", clear								
keep ibflopnr foddar fast`yr'

rename ibflopnr IBFLopNr					/* mat-merge Lisa */
merge 1:m IBFLopNr using "$source3\Louise_Lisa`yr'", keepusing(`inkforv' `KapInk' `inkdisp') keep(mat) nogen
duplicates drop IBFLopNr, force
rename `inkforv' inkf
rename `inkdisp' inkn
rename `KapInk' KapInk
replace KapInk = 0 if KapInk == .
gen inkt = inkf + KapInk
replace inkt = . if inkn == .					/* inkt and inkn simultaneously non-missing */
replace inkn = . if inkt == .
rename IBFLopNr ibflopnr

* Sample selection
replace inkt = . if fast`yr' == .		 		/* empty income without codes on property */
replace inkn = . if fast`yr' == . 				
gen age = `yr' - foddar									
replace inkt = . if age <= 19				/* empty income non-working age */
replace inkn = . if age <= 19				


replace inkt = 0 if inkt < 0
replace inkn = 0 if inkn < 0

replace inkt = inkt*10/${kpi}					/* income in real thousands */ 
replace inkn = inkn*10/${kpi}

rename inkt inkt`yr'
rename inkn inkn`yr'

keep ibflopnr inkt`yr' inkn`yr' 
save temp`yr', replace

end

* Loop program
genindinc 2017 ForvInk DispInk04 KapInk

compress
save "$input\indink", replace




***********************
*****   fastsd     ****
***********************
clear
set more off
sysdir set PLUS c:\ado\plus\b\
set scheme lean2

cd "D:\Userfiles\Personal\gabki722\Neighborhood Preferences\Matz"

global output "D:\Userfiles\Personal\gabki722\Neighborhood Preferences\Matz\Analysis\Output"
global input "D:\Userfiles\Personal\gabki722\Neighborhood Preferences\Matz\Analysis\Data"

global source "D:\Data\GeoSweden\GeoSweden 2.0\Fastighet"
global source2 "D:\Data\GeoSweden\GeoSweden 2.0\Basdata"
global source3 "D:\Data\GeoSweden\GeoSweden 2.0\Louise_Lisa"

******************************************************************************


** Program
capture program drop genfastsd
program genfastsd
args yr

* Input selected individuals in indfast
merge 1:1 ibflopnr using "$input\indfast", keepusing(fast`yr' foddar) nogen keep(mat)
rename fast`yr' fast

* Working age sample 
gen age = `yr' - foddar
drop if age < 20

drop if fast == .
drop age foddar

egen fastpopwa = count(ibflopnr), by(fast)

* Income
gen inkn = inkn`yr'

*Gen pc
centile inkn, centile(25 50 75)
global inknpc25 = r(c_1)
global inknpc50 = r(c_2)
global inknpc75 = r(c_3)

gen inkn1q = . 
replace inkn1q = 1 if inkn <= ${inknpc25}
replace inkn1q = 0 if inkn > ${inknpc25} & inkn != .
gen inkn2q = .
replace inkn2q = 1 if inkn <= ${inknpc50} & inkn > ${inknpc25}
replace inkn2q = 0 if inkn2q != 1 & inkn != .
gen inkn3q = .
replace inkn3q = 1 if inkn <= ${inknpc75} & inkn > ${inknpc50}
replace inkn3q = 0 if inkn3q != 1 & inkn != .
gen inkn4q = .
replace inkn4q = 1 if inkn > ${inknpc75} & inkn != .
replace inkn4q = 0 if inkn4q != 1 & inkn != .

* Calculate Sd 
egen fastinknm = mean(inkn), by(fast)
egen fastinkn1qm = mean(inkn1q), by(fast)
egen fastinkn2qm = mean(inkn2q), by(fast)
egen fastinkn3qm = mean(inkn3q), by(fast)
egen fastinkn4qm = mean(inkn4q), by(fast)

egen fastinkn1qt = total(inkn1q), by(fast)
egen fastinkn2qt = total(inkn2q), by(fast)
egen fastinkn3qt = total(inkn3q), by(fast)
egen fastinkn4qt = total(inkn4q), by(fast)

egen tot1 = total(inkn1q)
egen tot2 = total(inkn2q)
egen tot3 = total(inkn3q)
egen tot4 = total(inkn4q)

duplicates drop fast, force

gen year = `yr'
keep fast* year tot*
save temp`yr', replace

end


** Loop program
use "$input\indink", clear
keep(ibflopnr inkn2017)
genfastsd 2017

order fast year
sort fast year 
save "$input\fastsd", replace


***********************
*****     fastsoc   ****
***********************

clear
set more off
sysdir set PLUS c:\ado\plus\b\
set scheme lean2

cd "D:\Userfiles\Personal\gabki722\Neighborhood Preferences\Matz"

global output "D:\Userfiles\Personal\gabki722\Neighborhood Preferences\Matz\Analysis\Output"
global input "D:\Userfiles\Personal\gabki722\Neighborhood Preferences\Matz\Analysis\Data"

global source "D:\Data\GeoSweden\GeoSweden 2.0\Fastighet"
global source2 "D:\Data\GeoSweden\GeoSweden 2.0\Basdata"
global source3 "D:\Data\GeoSweden\GeoSweden 2.0\Louise_Lisa"

******************************************************************************

* Social welfare
use "$input\indfast", clear								
keep ibflopnr foddar fast2017
rename fast2017 fast

rename ibflopnr IBFLopNr					/* mat-merge Lisa */
merge 1:m IBFLopNr using "$source3\Louise_Lisa2017", keepusing(SocBidrPersF) keep(mat) nogen
duplicates drop IBFLopNr, force
gen socbid = 0
replace socbid = 1 if SocBidrPersF > 0
rename IBFLopNr ibflopnr

* Sample selection
gen age = 2017 - foddar									
drop if age <= 19				/* drop non-working age */
drop age foddar

* Gen mean by fast
drop if fast == .
egen fastsocm = mean(socbid), by(fast)

duplicates drop fast, force

gen year = 2017
keep fast* year

compress
save "$input\fastsoc", replace


***********************
*****   fast2017  ****
***********************
clear
set more off
sysdir set PLUS c:\ado\plus\b\
set scheme lean2

cd "D:\Userfiles\Personal\gabki722\Neighborhood Preferences\Matz"

global output "D:\Userfiles\Personal\gabki722\Neighborhood Preferences\Matz\Analysis\Output"
global input "D:\Userfiles\Personal\gabki722\Neighborhood Preferences\Matz\Analysis\Data"

global source "D:\Data\GeoSweden\GeoSweden 2.0\Fastighet"
global source2 "D:\Data\GeoSweden\GeoSweden 2.0\Basdata"
global source3 "D:\Data\GeoSweden\GeoSweden 2.0\Louise_Lisa"

******************************************************************************

* Properties 2017
use "$source\Fast2017", clear
keep IBFFastLopNr Typkod JurFormGrp
rename Typkod multi	
rename JurFormGrp jur	
rename IBFFastLopNr ibffastlopnr
order ibffastlopnr multi jur

******************************************************************************

*Cathegorize the values
gen own = 0
replace own = 1 if multi > 500 & multi != .
replace multi = 0 if multi < 300 & multi != 0
replace multi`i' = 1 if multi`i' >= 300 & multi`i' != .

gen private = 0
replace private = 1 if jur == 4 & own != 1 & multi == 1 | jur == 6 & own != 1 & multi == 1
replace own = 1 if jur == 7 & multi == 1
replace own = 0 if jur == 8
gen public = 0
replace public = 1 if jur == 1 & multi == 1 | jur == 2 & multi == 1 | jur == 8 & multi == 1

gen year = 2017
rename ibffastlopnr fast
drop jur

compress
save "$input\fast2017", replace


*****************************
***   graph_summarystat      *****
*****************************

clear
set more off
sysdir set PLUS c:\ado\plus\b\
set scheme lean2

cd "D:\Userfiles\Personal\gabki722\Neighborhood Preferences\Matz"

global output "D:\Userfiles\Personal\gabki722\Neighborhood Preferences\Matz\Analysis\Output"
global input "D:\Userfiles\Personal\gabki722\Neighborhood Preferences\Matz\Analysis\Data"
global input2 "D:\Userfiles\Projects\PoorHousing"

global source "D:\Data\GeoSweden\GeoSweden 2.0\Fastighet"
global source2 "D:\Data\GeoSweden\GeoSweden 2.0\Basdata"
global source3 "D:\Data\GeoSweden\GeoSweden 2.0\Louise_Lisa"

******************************************************************************

use "$input\fast2017", clear

* Merge with fastink data
merge 1:1 fast year using "$input\fastsd", keep(mat) nogen
merge 1:1 fast year using "$input\fastsoc", keepusing(fastsocm) nogen keep(mat)
rename fast id
merge 1:1 id using "$input2\FastRes", keepusing(residents2017) nogen keep(mat)
rename id fast
rename residents2017 residents

sort fast year
order fast year

******************************************************************************

** Gen sample
gen sample = .
replace sample = 1 if multi == 0
replace sample = 2 if public == 1
replace sample = 3 if private == 1
replace sample = 4 if own == 1
replace sample = 5 if sample == . /*others*/
replace multi = . if sample == 5

gen sample2 = 1 if multi == 0
replace sample2 = 2 if multi == 1
replace sample2 = 3 if sample2 == .

gen sample3 = 1 if sample == 2 | sample == 3
replace sample3 = 2 if sample3 == .

*****************************************************************************

*Gen share rich and poor
* POOR
bysort sample: egen poortype = total(fastinkn1qt)
bysort sample2: egen poortype2 = total(fastinkn1qt)
bysort sample3: egen poortype3 = total(fastinkn1qt)
gen sharepoor = poortype/tot1
gen sharepoor2 = poortype2/tot1
gen sharepoor3 = poortype3/tot1

* RICH
bysort sample: egen richtype = total(fastinkn4qt)
bysort sample2: egen richtype2 = total(fastinkn4qt)
bysort sample3: egen richtype3 = total(fastinkn4qt)
gen sharerich = richtype/tot4
gen sharerich2 = richtype2/tot4
gen sharerich3 = richtype3/tot4

******************************************************************************

mat A = J(7,7,.)

* Detached houses
egen residents_h = total(residents) if sample == 1
sum residents_h, d
mat A[1, 1] = round(r(mean),.001)

asgen fastinknm1 = fastinknm if sample == 1, w(fastpopwa)
sum fastinknm1, d
mat A[2, 1] = round(r(mean),.001)

asgen fastinkn1qm1 = fastinkn1qm if sample == 1, w(fastpopwa)
sum fastinkn1qm1, d
mat A[3, 1] = round(r(mean),.001)

asgen fastinkn4qm1 = fastinkn4qm if sample == 1, w(fastpopwa)
sum fastinkn4qm1, d
mat A[4, 1] = round(r(mean),.001)

asgen fastsocm1 = fastsocm if sample == 1, w(fastpopwa)
sum fastsocm1, d
mat A[5, 1] = round(r(mean),.001)

sum sharepoor if sample == 1, d
mat A[6, 1] = round(r(mean),.001)

sum sharerich if sample == 1, d
mat A[7, 1] = round(r(mean),.001)


* Multi-family houses
egen residents_mh = total(residents) if sample >= 2 & sample < 5
sum residents_mh, d
mat A[1, 2] = round(r(mean),.001)

asgen fastinknm2 = fastinknm if sample >= 2 & sample < 5, w(fastpopwa)
sum fastinknm2, d
mat A[2, 2] = round(r(mean),.001)

asgen fastinkn1qm2 = fastinkn1qm if sample >= 2 & sample < 5, w(fastpopwa)
sum fastinkn1qm2, d
mat A[3, 2] = round(r(mean),.001)

asgen fastinkn4qm2 = fastinkn4qm if sample >= 2 & sample < 5, w(fastpopwa)
sum fastinkn4qm2, d
mat A[4, 2] = round(r(mean),.001)

asgen fastsocm2 = fastsocm if sample >= 2 & sample < 5, w(fastpopwa)
sum fastsocm2, d
mat A[5, 2] = round(r(mean),.001)

sum sharepoor2 if sample2 == 2, d
mat A[6, 2] = round(r(mean),.001)

sum sharerich2 if sample2 == 2, d
mat A[7, 2] = round(r(mean),.001)


* Multi-family houses, rentals
egen residents_mhr = total(residents) if sample == 2 | sample == 3
sum residents_mhr, d
mat A[1, 3] = round(r(mean),.001)

asgen fastinknm3 = fastinknm if sample == 2 | sample == 3, w(fastpopwa)
sum fastinknm3, d
mat A[2, 3] = round(r(mean),.001)

asgen fastinkn1qm3 = fastinkn1qm if sample == 2 | sample == 3, w(fastpopwa)
sum fastinkn1qm3, d
mat A[3, 3] = round(r(mean),.001)

asgen fastinkn4qm3 = fastinkn4qm if sample == 2 | sample == 3, w(fastpopwa)
sum fastinkn4qm3, d
mat A[4, 3] = round(r(mean),.001)

asgen fastsocm3 = fastsocm if sample == 2 | sample == 3, w(fastpopwa)
sum fastsocm3, d
mat A[5, 3] = round(r(mean),.001)

sum sharepoor3 if sample3 == 1, d
mat A[6, 3] = round(r(mean),.001)

sum sharerich3 if sample3 == 1, d
mat A[7, 3] = round(r(mean),.001)


* Multi-family houses, public
egen residents_mhrpu = total(residents) if sample == 2
sum residents_mhrpu, d
mat A[1, 4] = round(r(mean),.001)

asgen fastinknm4 = fastinknm if sample == 2, w(fastpopwa)
sum fastinknm4, d
mat A[2, 4] = round(r(mean),.001)

asgen fastinkn1qm4 = fastinkn1qm if sample == 2, w(fastpopwa)
sum fastinkn1qm4, d
mat A[3, 4] = round(r(mean),.001)

asgen fastinkn4qm4 = fastinkn4qm if sample == 2, w(fastpopwa)
sum fastinkn4qm4, d
mat A[4, 4] = round(r(mean),.001)

asgen fastsocm4 = fastsocm if sample == 2, w(fastpopwa)
sum fastsocm4, d
mat A[5, 4] = round(r(mean),.001)

sum sharepoor if sample == 2, d
mat A[6, 4] = round(r(mean),.001)

sum sharerich if sample == 2, d
mat A[7, 4] = round(r(mean),.001)


* Multi-family houses, private
egen residents_mhrpr = total(residents) if sample == 3
sum residents_mhrpr, d
mat A[1, 5] = round(r(mean),.001)

asgen fastinknm5 = fastinknm if sample == 3, w(fastpopwa)
sum fastinknm5, d
mat A[2, 5] = round(r(mean),.001)

asgen fastinkn1qm5= fastinkn1qm if sample == 3, w(fastpopwa)
sum fastinkn1qm5, d
mat A[3, 5] = round(r(mean),.001)

asgen fastinkn4qm5 = fastinkn4qm if sample == 3, w(fastpopwa)
sum fastinkn4qm5, d
mat A[4, 5] = round(r(mean),.001)

asgen fastsocm5 = fastsocm if sample == 3, w(fastpopwa)
sum fastsocm5, d
mat A[5, 5] = round(r(mean),.001)

sum sharepoor if sample == 3, d
mat A[6, 5] = round(r(mean),.001)

sum sharerich if sample == 3, d
mat A[7, 5] = round(r(mean),.001)


* Multi-family houses, own
egen residents_mho = total(residents) if sample == 4
sum residents_mho, d
mat A[1, 6] = round(r(mean),.001)

asgen fastinknm6 = fastinknm if sample == 4, w(fastpopwa)
sum fastinknm6, d
mat A[2, 6] = round(r(mean),.001)

asgen fastinkn1qm6 = fastinkn1qm if sample == 4, w(fastpopwa)
sum fastinkn1qm6, d
mat A[3, 6] = round(r(mean),.001)

asgen fastinkn4qm6 = fastinkn4qm if sample == 4, w(fastpopwa)
sum fastinkn4qm6, d
mat A[4, 6] = round(r(mean),.001)

asgen fastsocm6 = fastsocm if sample == 4, w(fastpopwa)
sum fastsocm6, d
mat A[5, 6] = round(r(mean),.001)

sum sharepoor if sample == 4, d
mat A[6, 6] = round(r(mean),.001)

sum sharerich if sample == 4, d
mat A[7, 6] = round(r(mean),.001)


* Multi-family houses, other
egen residents_o = total(residents) if sample == 5
sum residents_o, d
mat A[1, 7] = round(r(mean),.001)

asgen fastinknm7 = fastinknm if sample == 5, w(fastpopwa)
sum fastinknm7, d
mat A[2, 7] = round(r(mean),.001)

asgen fastinkn1qm7 = fastinkn1qm if sample == 5, w(fastpopwa)
sum fastinkn1qm7, d
mat A[3, 7] = round(r(mean),.001)

asgen fastinkn4qm7 = fastinkn4qm if sample == 5, w(fastpopwa)
sum fastinkn4qm7, d
mat A[4, 7] = round(r(mean),.001)

asgen fastsocm7 = fastsocm if sample == 5, w(fastpopwa)
sum fastsocm7, d
mat A[5, 7] = round(r(mean),.001)

sum sharepoor if sample == 5, d
mat A[6, 7] = round(r(mean),.001)

sum sharerich if sample == 5, d
mat A[7, 7] = round(r(mean),.001)


mat colnames A = "Detached" "Multi" "Rentals" "Public" "Private" "Own" "Other"
mat rownames A = "Residents" "Disposable income" "Share Q1" "Share Q4" "Share soc" "Share poor" "Share rich"

sysdir set PLUS c:\ado\plus\
esttab m(A) using "$output\Matris_Matz.tex", replace title("Income by house type in 2017") ///
addnote("Table 1. Inflation adjusted income measured in thousands of SEK.")


**************************
**************************
***   Figure  A2   *****
**************************
**************************

*Lists with names of elected politicians (list updated as of 2020) and election results 2018 from val.se
*politicians adresses collected from eniro.se and coordinates collected via google maps
*Individual level information from val.se and info about coordinates saved in politicians.dta
*shape file of election districts from SCB ($map2018/swe")
clear all
loc set linnamarten //limar linnamarten
loc set2 Dropbox (Personal) // 
gl dat "/Users/`set'/`set2'/Politiker_geografi/politiker_kartor/data"
gl fig "/Users/`set'/`set2'/Politiker_geografi/politiker_kartor/figures"
gl map2018 "/Users/`set'/`set2'/Politiker_geografi/politiker_kartor/data/alla_valdistrikt_2018"
cap log close
log using "/Users/`set'/`set2'/Politiker_geografi/politiker_kartor/map.log", replace 


*election result
import excel "$dat/2018_K_per_valdistrikt.xlsx", sheet("K procent") cellrange(A1:Q6326) firstrow clear

ren LÄNSKOD lan
ren KOMMUNKOD kom
ren VALDISTRIKTSKOD vald

loc j 0
foreach x in lan kom vald {
loc ++j
tostring `x' ,replace
g t`j'=length(`x')
}
replace lan="0"+lan if t1==1
replace kom="0"+kom if t2==1
replace vald="0"+vald if t3==3
replace vald="00"+vald if t3==2
replace vald="000"+vald if t3==1

g VD=lan+kom+vald
g t4=length(VD)
tab t4
drop t1 t2 t3 t4


*check that it matches with the map
merge 1:1 VD using "$map2018/swe"
tab VALDISTRIKTSNAMN if _merge==1 // uppsamlingsdistrikt
drop if _merge==1

keep VD lan kom vald M C L KD S V MP SD 

sort VD
*drop if F=="Uppsamlingsdistrikt"
g id=_n

saveold "$dat/result_2018.dta", replace version(12)


*create map
use "$map2018/swe", clear
describe
merge 1:1 VD using "$dat/result_2018.dta"
drop _merge


g cons_votes= M+C+KD+L
g cons_votes_alt= ((M+C+KD+L)/(M+C+L+KD+S+V+MP))*100

gl add osize(thin) legt("Vote share Center-Right") legend(position(5)) legstyle(2) ocolor(white white white white white white white white white white)
colorpalette HCL bluered2, n(4) reverse nograph

spmap cons_votes_alt using  "$map2018/swecoord" if kom=="02" & lan=="14" , id(_ID)  fcolor(`r(p)')  title("Vote shares and politicians in Partille") ///
clm(c)  clb(20 40  50 60  80) $add ///
point(data("$dat/politicians.dta") select(drop if Kommun!="Partille"  ) ///
x(sweref99lon) y(sweref99lat) fcolor(edkblue maroon) by(party) legenda(on)  )
graph export "$fig/figA2.eps", replace

log close 

**************************
**************************
***   Figure  A 10   *****
**************************
**************************

* Created manually using data from Folke, O., & Rickne, J. (2020). All the single ladies: Job promotions and the durability of marriage. American Economic Journal: Applied Economics, 12(1), 260-287



********************************
********************************
***   Dataset homeowners   *****
********************************
********************************

set more off, perm
clear all

capture log close 

* log using "D:\UserFiles\Shared\Emigration\Native_flight\log\housetypes", replace 
log using "D:\UserFiles\Projects\Emigration\Native_flight\log\housetypes_new", replace 

cd "E:\GeoSweden\GeoSweden Stata\Alla register\Fastighet"
foreach year in 1990 1995{
clear all
use "fast`year'.dta", clear
rename IBFFastLopnr IBFFastLopNR
merge 1:m IBFFastLopNR using "beffast`year'.dta"

keep if _merge==3
drop _merge

gen tenure=5 
replace tenure=1 if JurFormGrp==4 &(Typkod>200 & Typkod<300) 
replace tenure=2 if JurFormGrp==7 
replace tenure=3 if JurFormGrp==8 & Typkod>200 
replace tenure=4 if JurFormGrp==4 & Typkod>300 
replace tenure=4 if JurFormGrp==6 & Typkod>300 
replace tenure=6 if JurFormGrp==4 & Typkod==120
replace tenure=7 if JurFormGrp==5 
 
label variable tenure tenure 
label define tenure 1 "owner-occupied" 2 "tenant-owner cooperative" 3 "public rental" 4 "private rental" 5 "other" 6 "agricultural" 7 "death"
label values tenure tenure

compress
save "D:\UserFiles\Projects\Emigration\Native_flight\data\housetypes_`year'.dta", replace
}

foreach year in 1996{
clear all
use "fast`year'.dta", clear
rename IBFFastLopnr IBFFastLopNr

bysort IBFFastLopNr: gen dup=cond(_N==1, 0, _n)
keep if dup==0| dup==1
drop dup

merge 1:m IBFFastLopNr using "beffast`year'.dta"

keep if _merge==3
drop _merge

rename JurformGrp JurFormGrp

gen tenure=5 
replace tenure=1 if JurFormGrp==4 &(Typkod>200 & Typkod<300) 
replace tenure=2 if JurFormGrp==7 
replace tenure=3 if JurFormGrp==8 & Typkod>200 
replace tenure=4 if JurFormGrp==4 & Typkod>300 
replace tenure=4 if JurFormGrp==6 & Typkod>300 
replace tenure=6 if JurFormGrp==4 & Typkod==120
replace tenure=7 if JurFormGrp==5 
 
label variable tenure tenure 
label define tenure 1 "owner-occupied" 2 "tenant-owner cooperative" 3 "public rental" 4 "private rental" 5 "other" 6 "agricultural" 7 "death"
label values tenure tenure

compress
save "D:\UserFiles\Projects\Emigration\Native_flight\data\housetypes_`year'.dta", replace
}


foreach year in 1997 1998 1999{
clear all
use "fast`year'.dta", clear
rename IBFFastLopnr IBFFastLopNr

bysort IBFFastLopNr: gen dup=cond(_N==1, 0, _n)
keep if dup==0| dup==1
drop dup

merge 1:m IBFFastLopNr using "beffast`year'.dta"

keep if _merge==3
drop _merge

gen tenure=5 
replace tenure=1 if JurFormGrp==4 &(Typkod>200 & Typkod<300) 
replace tenure=2 if JurFormGrp==7 
replace tenure=3 if JurFormGrp==8 & Typkod>200 
replace tenure=4 if JurFormGrp==4 & Typkod>300 
replace tenure=4 if JurFormGrp==6 & Typkod>300 
replace tenure=6 if JurFormGrp==4 & Typkod==120
replace tenure=7 if JurFormGrp==5 
 
label variable tenure tenure 
label define tenure 1 "owner-occupied" 2 "tenant-owner cooperative" 3 "public rental" 4 "private rental" 5 "other" 6 "agricultural" 7 "death"
label values tenure tenure

compress
save "D:\UserFiles\Projects\Emigration\Native_flight\data\housetypes_`year'.dta", replace
}

foreach year in 2000{
clear all
use "fast`year'.dta", clear
rename IBFFastLopnr IBFFastLopNR

bysort IBFFastLopNR: gen dup=cond(_N==1, 0, _n)
keep if dup==0| dup==1
drop dup

merge 1:m IBFFastLopNR using "beffast`year'.dta"

keep if _merge==3
drop _merge

gen tenure=5 
replace tenure=1 if JurFormGrp==4 &(Typkod>200 & Typkod<300) 
replace tenure=2 if JurFormGrp==7 
replace tenure=3 if JurFormGrp==8 & Typkod>200 
replace tenure=4 if JurFormGrp==4 & Typkod>300 
replace tenure=4 if JurFormGrp==6 & Typkod>300 
replace tenure=6 if JurFormGrp==4 & Typkod==120
replace tenure=7 if JurFormGrp==5 
 
label variable tenure tenure 
label define tenure 1 "owner-occupied" 2 "tenant-owner cooperative" 3 "public rental" 4 "private rental" 5 "other" 6 "agricultural" 7 "death"
label values tenure tenure

compress
save "D:\UserFiles\Projects\Emigration\Native_flight\data\housetypes_`year'.dta", replace
}


foreach year in 2001 2003 2004 2005 2006 2007 2008 2009 2010{
clear all
use "fast`year'.dta", clear
rename IBFFastLopnr IBFFastLopNr

bysort IBFFastLopNr: gen dup=cond(_N==1, 0, _n)
keep if dup==0| dup==1
drop dup

merge 1:m IBFFastLopNr using "beffast`year'.dta"

keep if _merge==3
drop _merge

gen tenure=5 
replace tenure=1 if JurFormGrp==4 &(Typkod>200 & Typkod<300) 
replace tenure=2 if JurFormGrp==7 
replace tenure=3 if JurFormGrp==8 & Typkod>200 
replace tenure=4 if JurFormGrp==4 & Typkod>300 
replace tenure=4 if JurFormGrp==6 & Typkod>300 
replace tenure=6 if JurFormGrp==4 & Typkod==120
replace tenure=7 if JurFormGrp==5 
 
label variable tenure tenure 
label define tenure 1 "owner-occupied" 2 "tenant-owner cooperative" 3 "public rental" 4 "private rental" 5 "other" 6 "agricultural" 7 "death"
label values tenure tenure

compress
save "D:\UserFiles\Projects\Emigration\Native_flight\data\housetypes_`year'.dta", replace
}

***Year 2002****

foreach year in 2002{
clear all
use "fast`year'_utan dubbletter.dta", clear
rename IBFFastLopNR IBFFastLopNr

bysort IBFFastLopNr: gen dup=cond(_N==1, 0, _n)
keep if dup==0| dup==1
drop dup

merge 1:m IBFFastLopNr using "beffast`year'.dta"

keep if _merge==3
drop _merge

gen tenure=5 
replace tenure=1 if JurFormGrp==4 &(Typkod>200 & Typkod<300) 
replace tenure=2 if JurFormGrp==7 
replace tenure=3 if JurFormGrp==8 & Typkod>200 
replace tenure=4 if JurFormGrp==4 & Typkod>300 
replace tenure=4 if JurFormGrp==6 & Typkod>300 
replace tenure=6 if JurFormGrp==4 & Typkod==120
replace tenure=7 if JurFormGrp==5 
 
label variable tenure tenure 
label define tenure 1 "owner-occupied" 2 "tenant-owner cooperative" 3 "public rental" 4 "private rental" 5 "other" 6 "agricultural" 7 "death"
label values tenure tenure

compress
save "D:\UserFiles\Projects\Emigration\Native_flight\data\housetypes_`year'.dta", replace
}

***Year 2011 to 2014****

foreach year in 2011 2012 2013 2014{
clear all
use "IBF_FastTax`year'.dta", clear
rename IBFFastLopnr IBFFastLopNr

bysort IBFFastLopNr: gen dup=cond(_N==1, 0, _n)
keep if dup==0| dup==1
drop dup

merge 1:m IBFFastLopNr using "IBF_Bef`year't.dta"

keep if _merge==3
drop _merge

gen tenure=5 
replace tenure=1 if JurFormGrp==4 &(Typkod>200 & Typkod<300) 
replace tenure=2 if JurFormGrp==7 
replace tenure=3 if JurFormGrp==8 & Typkod>200 
replace tenure=4 if JurFormGrp==4 & Typkod>300 
replace tenure=4 if JurFormGrp==6 & Typkod>300 
replace tenure=6 if JurFormGrp==4 & Typkod==120
replace tenure=7 if JurFormGrp==5 
 
label variable tenure tenure 
label define tenure 1 "owner-occupied" 2 "tenant-owner cooperative" 3 "public rental" 4 "private rental" 5 "other" 6 "agricultural" 7 "death"
label values tenure tenure

compress
save "D:\UserFiles\Projects\Emigration\Native_flight\data\housetypes_`year'.dta", replace
}

foreach year in 1990 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2013 2014 {
clear all
use "D:\UserFiles\Projects\Emigration\Native_flight\data\housetypes_`year'.dta", clear

rename *, lower

rename samsomrade sams

*Generate municipality variable 
gen str9 sams_string=string(sams, "%08.0f") 
gen municipality = substr(sams_string, 1, 4)
destring municipality, replace

 *Generate share owners
gen owner = 1 if tenure==1 | tenure==2
replace owner = 0 if tenure== 3| tenure== 4

 *Generate share rental
gen rental = 1 if tenure==3 | tenure==4
replace rental = 0 if tenure==1 | tenure==2 

bysort municipality: egen mean_owner_mun = mean(owner)
bysort sams: egen mean_owner_sams = mean(owner)

bysort municipality: egen mean_rental_mun = mean(rental)
bysort sams: egen mean_rental_sams = mean(rental)

gen year = `year'
order ibflopnr year sams

compress
save "D:\UserFiles\Projects\Emigration\Native_flight\data\housetypes_`year'.dta", replace
}

foreach year in 2011 2012{
clear all
use "D:\UserFiles\Projects\Emigration\Native_flight\data\housetypes_`year'.dta", clear

rename *, lower

rename samsomrade sams

*Generate municipality variable 
destring sams, generate (sams_string) force 
gen municipality = substr(sams, 1, 4)
destring municipality, replace

rename sams sams2
rename sams_string sams
rename sams2 sams_string
 *Generate share owners
gen owner = 1 if tenure==1 | tenure==2
replace owner = 0 if tenure== 3| tenure== 4

 *Generate share rental
gen rental = 1 if tenure==3 | tenure==4
replace rental = 0 if tenure==1 | tenure==2 

bysort municipality: egen mean_owner_mun = mean(owner)
bysort sams: egen mean_owner_sams = mean(owner)

bysort municipality: egen mean_rental_mun = mean(rental)
bysort sams: egen mean_rental_sams = mean(rental)

gen year = `year'
order ibflopnr year sams

compress
save "D:\UserFiles\Projects\Emigration\Native_flight\data\housetypes_`year'.dta", replace
}

foreach year in 2016 2017{
clear all
use "IBF_FastTax`year'.dta", clear

bysort ibffastlopnr_2015: gen dup=cond(_N==1, 0, _n)
keep if dup==0| dup==1
drop dup

merge 1:m ibffastlopnr_2015 using "IBF_Bef`year't.dta"

keep if _merge==3
drop _merge

gen tenure=5 
replace tenure=1 if jurformgrp==4 &(typkod>200 & typkod<300) 
replace tenure=2 if jurformgrp==7 
replace tenure=3 if jurformgrp==8 & typkod>200 
replace tenure=4 if jurformgrp==4 & typkod>300 
replace tenure=4 if jurformgrp==6 & typkod>300 
replace tenure=6 if jurformgrp==4 & typkod==120
replace tenure=7 if jurformgrp==5 
 
label variable tenure tenure 
label define tenure 1 "owner-occupied" 2 "tenant-owner cooperative" 3 "public rental" 4 "private rental" 5 "other" 6 "agricultural" 7 "death"
label values tenure tenure

rename ibffastlopnr_2015 ibffastlopnr

compress
save "D:\UserFiles\Projects\Emigration\Native_flight\data\housetypes_`year'.dta", replace
}

foreach year in 2016 2017{
clear all
use "D:\UserFiles\Projects\Emigration\Native_flight\data\housetypes_`year'.dta", clear

rename *, lower

 *Generate share owners
gen owner = 1 if tenure==1 | tenure==2
replace owner = 0 if tenure== 3| tenure== 4

 *Generate share rental
gen rental = 1 if tenure==3 | tenure==4
replace rental = 0 if tenure==1 | tenure==2 

gen year = `year'
order ibflopnr year 

compress
save "D:\UserFiles\Projects\Emigration\Native_flight\data\housetypes_`year'.dta", replace
}

foreach year in 1990 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2013 2014{
clear all
use "D:\UserFiles\Projects\Emigration\Native_flight\data\housetypes_`year'.dta", clear

gen rentalinclallbuild = 0
replace rentalinclallbuild = 1 if tenure==3 | tenure==4

gen ownerinclallbuild = 0
replace ownerinclallbuild = 1 if tenure==1 | tenure==2

bysort municipality: egen mean_owner_muninclallbuild = mean(ownerinclallbuild)
bysort sams: egen mean_owner_samsinclallbuild = mean(ownerinclallbuild)

bysort municipality: egen mean_rental_muninclallbuild = mean(rentalinclallbuild)
bysort sams: egen mean_rental_samsinclallbuild = mean(rentalinclallbuild)

order ibflopnr year 

compress
save "D:\UserFiles\Projects\Emigration\Native_flight\data\housetypes_`year'.dta", replace
}

foreach year in 2016 2017{
clear all
use "D:\UserFiles\Projects\Emigration\Native_flight\data\housetypes_`year'.dta", clear

gen rentalinclallbuild = 0
replace rentalinclallbuild = 1 if tenure==3 | tenure==4

gen ownerinclallbuild = 0
replace ownerinclallbuild = 1 if tenure==1 | tenure==2

order ibflopnr year 

compress
save "D:\UserFiles\Projects\Emigration\Native_flight\data\housetypes_`year'.dta", replace
}


foreach year in 1990 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2013 2014{
clear all
use "D:\UserFiles\Projects\Emigration\Native_flight\data\housetypes_`year'.dta", clear

collapse rentalinclallbuild ownerinclallbuild mean_owner_muninclallbuild mean_rental_muninclallbuild, by(municipality)

save "D:\UserFiles\Projects\Emigration\Native_flight\data\meanhousetypebymun_`year'.dta", replace
}

foreach year in 1990 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2013 2014{
clear all
use "D:\UserFiles\Projects\Emigration\Native_flight\data\housetypes_`year'.dta", clear

collapse rentalinclallbuild ownerinclallbuild, by(sams)

compress

save "D:\UserFiles\Projects\Emigration\Native_flight\data\meanhousetypebysams_`year'.dta", replace
}
